package mars.game.core;

import mars.game.util.Tools;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.view.MotionEvent;

public class Sprite
{
	
	public int life = 0;
	
	public int mAniIndex = 0;
	
	public int mDrawY = 0;
	
	public int mDrawX = 0;
	
	public int speedX = 0;
	
	public int speedY = 0;
	
	public int w = 0;
	
	public int h = 0;
	
	public int state = 0;
	
	public int sumIndexs;
	
	public Bitmap[] imgSprite;
	
	public int mCounts;
	
	public Sprite(int sumIndexs, int resId)
	{

		this.sumIndexs = sumIndexs;
		this.imgSprite = new Bitmap[sumIndexs];
		this.mAniIndex = 0;
		this.mCounts = 0;
		this.loadImage(resId);
	}
	
	public void setLife(int life)
	{

		// 可以根据等级和精灵初始化生命值
		this.life = life;
	}
	
	public void loadImage(int resId)
	{

		for (int i = 0; i < sumIndexs; i++)
		{
			imgSprite[i] = MarsRuntime.loadBitmap(resId + i);
		}
	}
	
	public void draw(Canvas canvas)
	{

		Bitmap imgSp = imgSprite[mAniIndex];
		w = imgSp.getWidth();
		h = imgSp.getHeight();
		// 若在屏幕内，则画出精灵
		if (this.isInScreen())
		{
			if(mAniIndex >=0 && mAniIndex < imgSprite.length)
			{
				canvas.drawBitmap(imgSp, mDrawX, mDrawY, null);
			}
			
		}
		
	}
	
	public void tick()
	{

		this.mCounts++;
		this.mDrawX += speedX;
		this.mDrawY += speedY;
	}
	
	public void setSpeed(int speedX, int speedY)
	{

		this.speedX = speedX;
		this.speedY = speedY;
	}
	
	public void setPos(int x, int y)
	{

		mDrawX = x;
		mDrawY = y;
	}
	
	public boolean isInScreen()
	{

		return Rect.intersects(Config.SCREEN_RECT, getRect());
	}
	
	public Rect getRect()
	{

		return new Rect(mDrawX, mDrawY, mDrawX + w, mDrawY + h);
		
	}
	
	public void onTouchEvent(MotionEvent event)
	{

		int x = (int) event.getX();
		int y = (int) event.getY();
		if (event.getAction() == MotionEvent.ACTION_DOWN)
		{
			if (Tools.pointInRect(x, y, this.getRect()))
			{
				// 如果受到攻击，生命值减1
				reduceLife();
			}
		}
		
	}
	
	// 判断生命值
	public boolean isDead()
	{

		if (this.life <= 0)
		{
			return true;
		}
		else
		{
			return false;
		}
	}
	
	public void reduceLife()
	{

		this.life = this.life - 1;
	}
}
